package com.mingmen.canting.gongyingshang;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Matrix;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.mingmen.canting.R;
import com.mingmen.canting.activity.FilterCompareActivity;
import com.mingmen.canting.base.BaseBean;
import com.mingmen.canting.definerecycleview.SwipeRecyclerView;
import com.mingmen.canting.defineview.DetailsMarkerView;
import com.mingmen.canting.http.callback.StringCallback;
import com.mingmen.canting.httpconfig.HttpResponse;
import com.mingmen.canting.immersionbar.ImmersionBar;
import com.mingmen.canting.model.ComPareDetailModel;
import com.mingmen.canting.model.GongCompareModel;
import com.mingmen.canting.model.QueryModel;
import com.mingmen.canting.util.DividerItemDecoration;
import com.mingmen.canting.util.GsonUtil;
import com.mingmen.canting.util.MyStringUtils;
import com.mingmen.canting.util.SharePreferenceUtil;
import com.mingmen.canting.zhexian.charting.charts.LineChart;
import com.mingmen.canting.zhexian.charting.components.Description;
import com.mingmen.canting.zhexian.charting.components.Legend;
import com.mingmen.canting.zhexian.charting.components.XAxis;
import com.mingmen.canting.zhexian.charting.components.YAxis;
import com.mingmen.canting.zhexian.charting.data.Entry;
import com.mingmen.canting.zhexian.charting.data.LineData;
import com.mingmen.canting.zhexian.charting.data.LineDataSet;
import com.mingmen.canting.zhexian.charting.formatter.ValueFormatter;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

public class GongYingCompareActivity extends FragmentActivity {

    @BindView(R.id.text_return)
    TextView textReturn;
    @BindView(R.id.img_right)
    ImageView imgRight;
    @BindView(R.id.tv_right)
    TextView tvRight;

    private Context mContext = this;
    private ArrayList<Fragment> mFragments = new ArrayList<>();

    @BindView(R.id.mToolbar)
    Toolbar mToolbar;
    @BindView(R.id.text_center)
    TextView text_center;
    @BindView(R.id.linear_return)
    LinearLayout linear_return;
    @BindView(R.id.text_liebiao)
    TextView text_liebiao;

    @BindView(R.id.text_compare)
    TextView text_compare;

    @BindView(R.id.recyclerview)
    SwipeRecyclerView recyclerview;
    private LinearLayoutManager mLinearLayoutManager;
    GongYingCompareLeftAdapter gongYingCompareLeftAdapter;


    String token;
    List<ComPareDetailModel.DataBean> dataBeanList = new ArrayList<>();
    @BindView(R.id.text_search)
    TextView text_search;
    @BindView(R.id.main_search)
    EditText main_search;

    TimePickerView pvTime, pvTime2;
    @BindView(R.id.textview_calendafirst)
    TextView textview_calendafirst;
    @BindView(R.id.textview_calendasecond)
    TextView textview_calendasecond;

    @BindView(R.id.layout_nodata)
    LinearLayout layout_nodata;
    @BindView(R.id.layout_calenda_first)
    LinearLayout layout_calenda_first;
    @BindView(R.id.layout_calenda_second)
    LinearLayout layout_calenda_second;
    String startTime = "";
    String endTime = "";
    @BindView(R.id.layout_sop)
    LinearLayout layout_sop;
    @BindView(R.id.text_shopName)
    TextView text_shopName;

    @BindView(R.id.lineChart)
    LineChart lineChart;
    List<Entry> listOne = new ArrayList<>();
    List<Entry> listTwo = new ArrayList<>();
    @BindView(R.id.layout_lineChart)
    LinearLayout layout_lineChart;
    String commodityId = "";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gongyingcompare);
        ButterKnife.bind(this);

        ImmersionBar.with(this).titleBar(mToolbar)
                .navigationBarColor(R.color.black).init();
        token = (String) SharePreferenceUtil.get(this, "token", "");
        text_center.setText("商品比价");

        mLinearLayoutManager = new LinearLayoutManager(this);
        recyclerview.setLayoutManager(mLinearLayoutManager);
        DividerItemDecoration itemDecorationHeader = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST);
        itemDecorationHeader.setDividerDrawable(ContextCompat.getDrawable(this, R.drawable.divider_main_bg_height_1));
        recyclerview.addItemDecoration(itemDecorationHeader);
        gongYingCompareLeftAdapter = new GongYingCompareLeftAdapter(this, dataBeanList);
        recyclerview.setAdapter(gongYingCompareLeftAdapter);
        recyclerview.setVisibility(View.GONE);
        layout_nodata.setVisibility(View.VISIBLE);
        getCaneda();
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String data = dateFormat.format(calendar.getTime());
        startTime = data;
        endTime = data;

        textview_calendafirst.setText(data);
        textview_calendasecond.setText(data);
        layout_sop.setVisibility(View.GONE);
    }

    XAxis xAxis;
    LineDataSet one;
    YAxis axisLeft;

    @OnClick({R.id.text_return, R.id.img_right, R.id.tv_right, R.id.linear_return, R.id.text_liebiao, R.id.text_compare, R.id.text_search, R.id.layout_calenda_first, R.id.layout_calenda_second,})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.text_return:
            case R.id.linear_return:
                finish();

                break;
            case R.id.img_right:
                break;
            case R.id.tv_right:
                break;

            case R.id.text_liebiao:
                text_liebiao.setBackground(getResources().getDrawable(R.drawable.shape_productleft));

                text_compare.setBackground(getResources().getDrawable(R.drawable.shape_productright));
                text_liebiao.setTextColor(getResources().getColor(R.color.white));
                text_compare.setTextColor(Color.parseColor("#2E2E2E"));
                getQueryCommodity(token, main_search.getText().toString());
                break;

            case R.id.text_compare:
                text_compare.setBackground(getResources().getDrawable(R.drawable.shape_productleft2));

                text_liebiao.setBackground(getResources().getDrawable(R.drawable.shape_productright2));
                text_compare.setTextColor(getResources().getColor(R.color.white));
                text_liebiao.setTextColor(Color.parseColor("#2E2E2E"));
                recyclerview.setVisibility(View.GONE);
                if (commodityId.equals("")) {
                    Toast.makeText(mContext, "请选择商品", Toast.LENGTH_SHORT).show();
                } else {
                    HttpResponse.comparePriceLine(token, startTime, endTime, commodityId, new StringCallback(GongYingCompareActivity.this) {
                        @Override
                        public void onSuccess(String s, Call call, Response response) {
                            Log.d("comparePriceLine", s);

                            List<String> arriveDate = new ArrayList<>();

                            GongCompareModel gongCompareModel = new GongCompareModel();
                            gongCompareModel = GsonUtil.GsonToBean(s, GongCompareModel.class);
                            List<GongCompareModel.DataBean.PriceListBean> priceListBeans = new ArrayList<>();

                            List<GongCompareModel.DataBean.PriceListBean.SubPriceLineBean> subPriceLineBeanArrayList = new ArrayList<>();


                            if (priceListBeans.size() > 0) {
                                priceListBeans.clear();
                            }
                            priceListBeans = gongCompareModel.getData().get(0).getPriceList();

                            for (int i = 0; i < priceListBeans.size(); i++) {
                                if (priceListBeans.get(i).getSubPriceLine().size() == 0) {

                                } else {
                                    subPriceLineBeanArrayList.addAll(priceListBeans.get(i).getSubPriceLine());
                                }


                            }

                            if (subPriceLineBeanArrayList.size() == 0) {
                                layout_lineChart.setVisibility(View.GONE);
                                layout_nodata.setVisibility(View.VISIBLE);
                                Toast.makeText(mContext, "当前无比价信息", Toast.LENGTH_SHORT).show();
                            } else {

                                if (priceListBeans.size() == 0) {
                                    layout_lineChart.setVisibility(View.GONE);
                                    layout_nodata.setVisibility(View.VISIBLE);
                                } else {
                                    if (priceListBeans.size() > 0) {
                                        layout_nodata.setVisibility(View.GONE);
                                        recyclerview.setVisibility(View.GONE);
                                        layout_lineChart.setVisibility(View.VISIBLE);
                                        arriveDate.clear();
                                        listOne.clear();
                                    } else {
                                        layout_lineChart.setVisibility(View.GONE);

                                    }

                                    for (int i = 0; i < priceListBeans.size(); i++) {
                                        arriveDate.add(priceListBeans.get(i).getArriveDate());
                                    }

                                    for (int i = 0; i < priceListBeans.size(); i++) {
                                        listOne.add(new Entry(i, priceListBeans.get(i).getPrice()));
                                    }
                                    Legend legend = lineChart.getLegend();
                                    legend.setEnabled(false);

                                    one = new LineDataSet(listOne, "One");//将数据赋值到你的线条上

                                    one = new LineDataSet(listOne, "");//将数据赋值到你的线条上

                                    one.setColor(Color.parseColor("#626666"));//设置线的颜色
//        one.setColor(Color.DKGRAY);
                                    // 显示的圆形的大小
                                    one.setCircleSize(5.0f);
                                    // 圆球的颜色
//        #BA0017
//        one.setCircleColor(Color.GREEN);
                                    one.setCircleColor(getResources().getColor(R.color.normal_red));
                                    one.setCircleHoleColor(getResources().getColor(R.color.normal_red));
                                    one.setDrawValues(false);
                                    one.setDrawFilled(false); //设置折线图下方颜色填充默认是蓝色

                                    one.setDrawHighlightIndicators(false);
                                    // 点击后，十字交叉线的颜色
                                    one.setHighLightColor(Color.TRANSPARENT);
                                    LineData lineData = new LineData();// //线的总管理
                                    lineData.addDataSet(one);//每加一条就add一次
                                    lineChart.setData(lineData);//把线条设置给你的lineChart上
                                    lineChart.invalidate();//刷新

                                    xAxis = lineChart.getXAxis();//得到x轴
                                    xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);//设置x轴的位置，在整个图形的底部
                                    xAxis.setLabelCount(listOne.size(), false); //设置X轴刻度 第一个参数是想要x轴有多少条刻度,第二个参数true是将刻度数设置为你的第一个参数的数量 ，false是将刻度数设置为你的第一个参数的数量+1（0.0点也要算哦）
                                    xAxis.setGranularity(1f);//设置x轴坐标间的最小间距
                                    xAxis.setAxisMaximum(listOne.size() - 1);//设置x轴的最大范围
                                    xAxis.setAxisMinimum(0f);//设置x轴的最小范围
//        xAxis.setYOffset(50f);
                                    xAxis.setDrawGridLines(true);//绘制网格线
                                    xAxis.setAxisLineWidth(1.5f);


                                    xAxis.setValueFormatter(new ValueFormatter() {

                                        @Override
                                        public String getFormattedValue(float value) {
                                            Log.d("valuex", (int) value + "");

                                            if ((int) value == 0) {
                                                one.setCircleColor(getResources().getColor(R.color.transparent));
                                                return "";
                                            } else {
                                                one.setCircleColor(getResources().getColor(R.color.normal_red));
                                                //设置是否绘制刻度
                                                xAxis.setDrawScale(true);

                                                return arriveDate.get((int) value);

                                            }
                                        }
                                    });

///取消左下角描述
                                    lineChart.getDescription().setEnabled(true);

                                    Description description = new Description();
                                    description.setText("时间");
                                    lineChart.setDescription(description);
                                    //Y轴不是有左右两边嘛，这就是获取左右两边的y轴
                                    YAxis left = lineChart.getAxisLeft();
                                    //是否绘制0所在的网格线/默认false绘制
                                    left.setDrawGridLines(true);//绘制网格线
                                    left.setDrawZeroLine(true);
                                    //将网格线设置为虚线模式
//        left.enableGridDashedLine(10f, 10f, 0f);
                                    //获取图表右边y轴
                                    YAxis right = lineChart.getAxisRight();
                                    //禁用图表右边y轴
                                    right.setEnabled(false);

                                    YAxis axisRight = lineChart.getAxisRight();
                                    axisLeft = lineChart.getAxisLeft();
                                    axisRight.setEnabled(false);//将右边的y轴隐藏
                                    //y轴最大值最小值范围
//        axisLeft.setAxisMaximum(550f);
                                    axisLeft.setDrawGridLines(true);
//        axisLeft.setAxisMaximum(15);
                                    axisLeft.setAxisMaximum(20f);
                                    axisLeft.setAxisMinimum(0f);
//        axisLeft.setLabelCount(3, true);

                                    //文字颜色
                                    axisLeft.setTextColor(Color.parseColor("#000000"));//设置左y轴字的颜色
                                    axisLeft.setAxisLineColor(Color.BLACK);//y轴颜色
                                    axisLeft.setDrawZeroLine(true); // draw a zero line
                                    axisLeft.setZeroLineColor(Color.GRAY);
                                    axisLeft.setZeroLineWidth(1.5f);
                                    axisLeft.setAxisLineWidth(1.5f);
                                    axisLeft.setAxisLineColor(Color.GRAY);
                                    axisLeft.setMinWidth(5f);
//        axisLeft.setDrawTopYLabelEntry(false);
                                    axisLeft.setValueFormatter(new
                                                                       ValueFormatter() {
                                                                           @Override
                                                                           public String getFormattedValue(float value) {
                                                                               xAxis.setDrawScale(true);
                                                                               axisLeft.setDrawScale(true);
                                                                               if (value == 0) {
                                                                                   return "";
                                                                               } else {
                                                                                   return super.getFormattedValue(value);
                                                                               }


                                                                           }
                                                                       });

                                    Matrix m = new Matrix();
//        m.postScale(3.5f, 1f);//两个参数分别是x,y轴的缩放比例。例如：将x轴的数据放大为之前的1.5倍
                                    m.postScale(1.5f, 1f);//两个参数分别是x,y轴的缩放比例。例如：将x轴的数据放大为之前的1.5倍
                                    lineChart.getViewPortHandler().refresh(m, lineChart, false);//将图表动画显示之前进行缩放

                                    lineChart.animateX(1000); // 立即执行的动画,x轴
                                    lineChart.setDragEnabled(true);// 是否可以拖拽

                                    lineChart.setScaleEnabled(false);// 是否可以缩放 x和y轴, 默认是true
                                    lineChart.setScaleXEnabled(false); //是否可以缩放 仅x轴
                                    lineChart.setScaleYEnabled(false); //是否可以缩放 仅y轴

                                    axisLeft.setDrawTopYLabelEntry(false);
                                    axisLeft.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
                                    List<GongCompareModel.DataBean.PriceListBean> finalPriceListBeans = priceListBeans;
                                    DetailsMarkerView detailsMarkerView = new DetailsMarkerView(GongYingCompareActivity.this, new ValueFormatter() {
                                        @Override
                                        public String getFormattedValue(float value) {
                                            Log.d("mark", "mark" + value);
//                                priceListBeans.get(value).getSubPriceLine();
                                            Intent intent = new Intent(GongYingCompareActivity.this, FilterCompareActivity.class);

                                            int position = (int) value;
                                            intent.putExtra("subPriceLine", MyStringUtils.beanToString(finalPriceListBeans.get(position).getSubPriceLine()));

                                            startActivity(intent);

                                            return super.getFormattedValue(value);
                                        }
                                    });

                                    detailsMarkerView.setChartView(lineChart);
                                    lineChart.setMarker(detailsMarkerView);
                                }


                            }


                        }
                    });
                }


                break;
            case R.id.text_search:
                if (TextUtils.isEmpty(main_search.getText().toString().trim())) {
                    Toast.makeText(this, "请输入商品", Toast.LENGTH_SHORT).show();
                } else {
                    getQueryCommodity(token, main_search.getText().toString());
                }


                break;
            case R.id.layout_calenda_first:
                pvTime.show(layout_calenda_first);
                break;
            case R.id.layout_calenda_second:
                pvTime.show(layout_calenda_second);
                break;
        }
    }

    List<QueryModel.DataBean> queryList = new ArrayList<>();


    public void getQueryCommodity(String token, String keyword) {
        HttpResponse.queryCommodity(token, keyword, new StringCallback(this) {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                Log.d("getQueryCommodity", s);
                BaseBean baseBean = new BaseBean();
                baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                if (baseBean.getCode() == 0) {
                    QueryModel queryModel = new QueryModel();
                    queryModel = GsonUtil.GsonToBean(s, QueryModel.class);
                    queryList.addAll(queryList);
                    if (queryList.size() > 0) {
                        layout_nodata.setVisibility(View.GONE);
                        recyclerview.setVisibility(View.VISIBLE);
                        layout_lineChart.setVisibility(View.GONE);
                        commodityId = queryModel.getData().get(0).getCommodityId();
                        text_shopName.setText(main_search.getText().toString());
                        comparePrice(token, startTime, endTime, commodityId);

                    } else {
                        layout_lineChart.setVisibility(View.GONE);
                    }


                }


            }
        });
    }

    public void comparePrice(String token, String startDate, String endDate, String commodityId) {
        HttpResponse.comparePrice(token, startDate, endDate, commodityId, new StringCallback(GongYingCompareActivity.this) {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                Log.d("GongYingCompare", s);

                ComPareDetailModel comPareDetailModel = new ComPareDetailModel();
                comPareDetailModel = GsonUtil.GsonToBean(s, ComPareDetailModel.class);
                if (comPareDetailModel.getData().size() > 0) {
                    recyclerview.setVisibility(View.VISIBLE);
                    layout_nodata.setVisibility(View.GONE);
                    dataBeanList.addAll(comPareDetailModel.getData());
                    gongYingCompareLeftAdapter.setDataList(dataBeanList);
                } else {
                    Toast.makeText(mContext, "当前商品无数据", Toast.LENGTH_SHORT).show();
                    recyclerview.setVisibility(View.GONE);
                    layout_nodata.setVisibility(View.VISIBLE);
                }

            }
        });
    }


    public void getCaneda() {
        Calendar selectedDate = Calendar.getInstance();//系统当前时间
        Calendar startDate = Calendar.getInstance();
        startDate.set(2020, 1, 1);
        Calendar endDate = Calendar.getInstance();
        int y = endDate.get(Calendar.YEAR);
        int m = endDate.get(Calendar.MONTH);
        int d = endDate.get(Calendar.DATE);
        endDate.set(y, m, d);
        pvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                switch (v.getId()) {
                    case R.id.layout_calenda_first:
                        textview_calendafirst.setText(getTime(date));
                        startTime = getTime(date);
                        Integer i = startTime.compareTo(endTime);
                        if (i > 0) {
                            Toast.makeText(GongYingCompareActivity.this, "开始时间不能大于结束时间", Toast.LENGTH_SHORT).show();
                        } else {
                            getQueryCommodity(token, main_search.getText().toString());
                        }

                        break;
                    case R.id.layout_calenda_second:

                        endTime = getTime(date);
                        Integer i1 = startTime.compareTo(endTime);
                        if (i1 > 0) {
                            Toast.makeText(GongYingCompareActivity.this, "开始时间不能大于结束时间", Toast.LENGTH_SHORT).show();
                        } else {
                            textview_calendasecond.setText(getTime(date));
                            getQueryCommodity(token, main_search.getText().toString());
                        }

                        break;
                }


            }
        }).setDate(selectedDate)
                .setRangDate(startDate, endDate)
                .setLayoutRes(R.layout.pickerview_custom_lunar, new CustomListener() {

                    @Override
                    public void customLayout(final View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvTime.returnData();
                                pvTime.dismiss();
                            }
                        });
                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvTime.dismiss();
                            }
                        });


                    }


                })
                .setType(new boolean[]{true, true, true, false, false, false})
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setDividerColor(getResources().getColor(R.color.canedacolor))

                .build();
    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
        Log.d("getTime()", "choice date millis: " + date.getTime());
//        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }

}
